package com.eqs.enterprisequestionnaire.service;

import com.eqs.enterprisequestionnaire.model.pojo.Answer;
import com.eqs.enterprisequestionnaire.model.pojo.Question;
import com.eqs.enterprisequestionnaire.model.pojo.Response;
import com.eqs.enterprisequestionnaire.model.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.eqs.enterprisequestionnaire.model.enums.QuestionEnum.isLevelType;
@Service
public class DifferenceLevelQuestionAnalysisService {
    @Autowired
    private QuestionService questionService;

    @Autowired
    private HistoryService historyService;

    @Autowired
    private UserService userService;

    @Autowired
    private ResponseService responseService;


    // 性别差异化分析
    public Map<Boolean, Double> getGenderDifference(Integer questionId) {
        Question question = questionService.selectByQuestionId(questionId);
        if (!isLevelType(question.getType())) {
            return null;
        }

        List<Answer> answers = historyService.getListAnswerByQuestionId(questionId);
        Map<Boolean, Integer> totalScores = new HashMap<>();
        Map<Boolean, Integer> countAnswers = new HashMap<>();

        for (Answer answer : answers) {
            Response response = responseService.getById(answer.getResponseId());
            User user = userService.getById(response.getUserId());
            Boolean gender = user.getGender();

            totalScores.put(gender, totalScores.getOrDefault(gender, 0) + Integer.parseInt(answer.getText()));
            countAnswers.put(gender, countAnswers.getOrDefault(gender, 0) + 1);
        }

        Map<Boolean, Double> result = new HashMap<>();
        for (Map.Entry<Boolean, Integer> entry : totalScores.entrySet()) {
            Boolean gender = entry.getKey();
            Integer totalScore = entry.getValue();
            Integer count = countAnswers.get(gender);
            result.put(gender, count == 0 ? 0.0 : (double) totalScore / count);
        }

        return result;
    }

    // 年龄差异化分析
    public Map<String, Double> getAgeDifference(Integer questionId) {
        Question question = questionService.selectByQuestionId(questionId);

        // 判断是否为排序题类型
        if (!isLevelType(question.getType())) {
            return null;
        }

        // 获取该问题的所有答案
        List<Answer> answers = historyService.getListAnswerByQuestionId(questionId);

        Map<String, Integer> totalScores = new HashMap<>();
        Map<String, Integer> countAnswers = new HashMap<>();

        // 初始化年龄阶段
        String[] ageStages = {"20-25", "25-30", "30-35","35-40","40-45","45-50","50+"};
        for (String ageStage : ageStages) {
            totalScores.put(ageStage, 0);
            countAnswers.put(ageStage, 0);
        }

        for (Answer answer : answers) {
            Response response = responseService.getById(answer.getResponseId());
            User user = userService.getById(response.getUserId());
            int age = userService.calculateUserAge(user.getId());

            String ageStage = null;
            if (age >= 20 && age <= 25) {
                ageStage = "20-25";
            } else if (age > 25 && age <= 30) {
                ageStage = "25-30";
            } else if (age > 30 && age <= 35) {
                ageStage = "30-35";
            }else if (age > 35 && age <= 40) {
                ageStage = "35-40";
            }else if (age > 40 && age <= 45) {
                ageStage = "40-45";
            }else if (age > 45 && age <= 50) {
                ageStage = "45-50";
            }else if (age > 50) {
                ageStage = "50+";
            }

            if (ageStage != null) {
                totalScores.put(ageStage, totalScores.get(ageStage) + Integer.parseInt(answer.getText()));
                countAnswers.put(ageStage, countAnswers.get(ageStage) + 1);
            }
        }

        Map<String, Double> result = new HashMap<>();
        for (String ageStage : ageStages) {
            int totalScore = totalScores.get(ageStage);
            int count = countAnswers.get(ageStage);
            result.put(ageStage, count == 0 ? 0.0 : (double) totalScore / count);
        }

        return result;
    }

    // 公司差异化分析
    public Map<String, Double> getEnterpriseDifference(Integer questionId) {
        Question question = questionService.selectByQuestionId(questionId);
        if (!isLevelType(question.getType())) {
            return null;
        }

        List<Answer> answers = historyService.getListAnswerByQuestionId(questionId);
        Map<String, Integer> totalScores = new HashMap<>();
        Map<String, Integer> countAnswers = new HashMap<>();

        for (Answer answer : answers) {
            Response response = responseService.getById(answer.getResponseId());
            User user = userService.getById(response.getUserId());
            String enterprise = user.getEnterprise();

            totalScores.put(enterprise, totalScores.getOrDefault(enterprise, 0) + Integer.parseInt(answer.getText()));
            countAnswers.put(enterprise, countAnswers.getOrDefault(enterprise, 0) + 1);
        }

        Map<String, Double> result = new HashMap<>();
        for (Map.Entry<String, Integer> entry : totalScores.entrySet()) {
            String enterprise = entry.getKey();
            Integer totalScore = entry.getValue();
            Integer count = countAnswers.get(enterprise);
            result.put(enterprise, count == 0 ? 0.0 : (double) totalScore / count);
        }

        return result;
    }

    // 职位差异化分析
    public Map<String, Double> getRoleDifference(Integer questionId) {
        Question question = questionService.selectByQuestionId(questionId);
        if (!isLevelType(question.getType())) {
            return null;
        }

        List<Answer> answers = historyService.getListAnswerByQuestionId(questionId);
        Map<String, Integer> totalScores = new HashMap<>();
        Map<String, Integer> countAnswers = new HashMap<>();

        for (Answer answer : answers) {
            Response response = responseService.getById(answer.getResponseId());
            User user = userService.getById(response.getUserId());
            String role = user.getRoleName();

            totalScores.put(role, totalScores.getOrDefault(role, 0) + Integer.parseInt(answer.getText()));
            countAnswers.put(role, countAnswers.getOrDefault(role, 0) + 1);
        }

        Map<String, Double> result = new HashMap<>();
        for (Map.Entry<String, Integer> entry : totalScores.entrySet()) {
            String role = entry.getKey();
            Integer totalScore = entry.getValue();
            Integer count = countAnswers.get(role);
            result.put(role, count == 0 ? 0.0 : (double) totalScore / count);
        }

        return result;
    }

    public Map<Boolean, Map<Integer, Double>> getGenderLevelProportions(Integer questionId) {
        return getLevelProportionsByAttribute(questionId, "gender");
    }

    public Map<String, Map<Integer, Double>> getEnterpriseLevelProportions(Integer questionId) {
        return getLevelProportionsByAttribute(questionId, "enterprise");
    }

    public Map<String, Map<Integer, Double>> getRoleLevelProportions(Integer questionId) {
        return getLevelProportionsByAttribute(questionId, "role");
    }

    public Map<String, Map<Integer, Double>> getAgeLevelProportions(Integer questionId) {
        return getLevelProportionsByAttribute(questionId, "age");
    }

    private Map getLevelProportionsByAttribute(Integer questionId, String attribute) {
        Question question = questionService.selectByQuestionId(questionId);

        if (!isLevelType(question.getType())) {
            return null;
        }

        List<Answer> answers = historyService.getListAnswerByQuestionId(questionId);

        Map<Object, Map<Integer, Integer>> levelCounts = new HashMap<>();
        Map<Object, Integer> totalAnswers = new HashMap<>();

        for (Answer answer : answers) {
            Response response = responseService.getById(answer.getResponseId());
            User user = userService.getById(response.getUserId());
            Object key = getUserAttribute(user, attribute);

            if (key != null) {
                levelCounts.putIfAbsent(key, new HashMap<>());
                totalAnswers.putIfAbsent(key, 0);
                int level = Integer.parseInt(answer.getText());
                levelCounts.get(key).put(level, levelCounts.get(key).getOrDefault(level, 0) + 1);
                totalAnswers.put(key, totalAnswers.get(key) + 1);
            }
        }

        Map<Object, Map<Integer, Double>> levelProportions = new HashMap<>();
        for (Map.Entry<Object, Map<Integer, Integer>> entry : levelCounts.entrySet()) {
            Object key = entry.getKey();
            Map<Integer, Integer> counts = entry.getValue();
            Map<Integer, Double> proportions = new HashMap<>();
            int total = totalAnswers.get(key);
            for (int i = 1; i <= 5; i++) {
                int count = counts.getOrDefault(i, 0);
                proportions.put(i, total == 0 ? 0.0 : (double) count / total);
            }
            levelProportions.put(key, proportions);
        }

        return levelProportions;
    }

    private Object getUserAttribute(User user, String attribute) {
        switch (attribute) {
            case "gender":
                return user.getGender();
            case "enterprise":
                return user.getEnterprise();
            case "role":
                return user.getRoleName();
            case "age":
                int age = userService.calculateUserAge(user.getId());
                if (age >= 20 && age <= 25) {
                    return "20-25";
                } else if (age > 25 && age <= 30) {
                    return "25-30";
                } else if (age > 30 && age <= 35) {
                    return "30-35";
                }else if (age > 35 && age <= 40) {
                    return "35-40";
                }else if (age > 40 && age <= 45) {
                    return "40-45";
                }else if (age > 45 && age <= 50) {
                    return "45-50";
                }else if (age > 50) {
                    return "50+";
                }
                return null;
            default:
                throw new IllegalArgumentException("Unknown attribute: " + attribute);
        }
    }
}
